#include "app_mqtt.h"
#include "MQTTClient.h"
#include "string.h"
#include "log.h"
#include "errno.h"

static MQTTClient client;
static MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer; // MQTT客户端连接选项
static MQTTClient_message pubmsg = MQTTClient_message_initializer;  

/**
 * 失联回调
 */
static void app_mqtt_lost_callback(void *context, char *cause)
{
    log_error("MQTTClient_lost_callback: %s\n", cause);
}

// 声明一个 回调函数用于 注册一个接收数据的回调函数
static  int (*recv_callback)(char *data);

/**
 * 收到数据回调
 */
static int app_mqtt_recieve_callback(void *context, char *topicName, int topicLen, MQTTClient_message *message)
{
    log_info("MQTTClient_recieve_callback: %s\n", topicName);
    int status =1;
    int ret= recv_callback(message->payload);
    if (ret != 0)
    {   
         log_error(" 接收数据处理失败: %s\n", message->payload);
         status=0; // 失败
    }

    return status;  //成功是1  失败是0
}

/**
 * 发送成功回调
 */
static void app_mqtt_sent_callback(void *context,int token)
{
    log_info("MQTTClient_sent_success !!  \n");
}

/**
 * @brief   MQTT客户端的初始化
 * 1  创建一个MQTT客户端
 * 2  设置d回调函数   1 失联 2  收到数据 3 发送成功
 * 3  连接客户端
 * 4   订阅主题
 *
 */
int app_mqtt_init(void)
{
    // * 1  创建一个MQTT客户端
    int ret = MQTTClient_create(&client, MQTT_ADDRESS, MQTT_CLIENT_ID, MQTTCLIENT_PERSISTENCE_NONE, NULL);
    if (ret != MQTTCLIENT_SUCCESS)
    {
        perror("MQTTClient_create");
        return -1;
    }
    //* 2  设置回调函数   1 失联 2  收到数据 3 发送成功
    MQTTClient_setCallbacks(client, NULL, app_mqtt_lost_callback, app_mqtt_recieve_callback, app_mqtt_sent_callback);
    //* 3  连接客户端
    ret = MQTTClient_connect(client, &conn_opts);
    if (ret != MQTTCLIENT_SUCCESS)
    {
        perror("MQTTClient_connect");
        MQTTClient_destroy(&client);
        return -1;
    }

    //* 4   订阅主题
    ret= MQTTClient_subscribe(client, MQTT_RECV_TOPIC, MQTT_QOS);
    if(ret!=MQTTCLIENT_SUCCESS)
    {
        perror("MQTTClient_subscribe");
        //销毁客户端
        app_mqtt_destroy();
        return -1;
    }
    return 0;


}

/**
 *  向一个主题发送数据
 */
int app_mqtt_send(char *data)
{   
    pubmsg.payload = data;
    pubmsg.payloadlen = strlen(data);
    int  ret=  MQTTClient_publishMessage(client ,MQTT_SEND_TOPIC, &pubmsg, 0 );
    if(ret!=MQTTCLIENT_SUCCESS)
    {
        perror("MQTTClient_publishMessage");
        return -1;
    }
    return 0;
}



/**
 * @brief  注册一个接收数据的回调函数
 */
int app_mqtt_register_recv_callback(int (*callback)(char *data))
{
    recv_callback=callback;
    return 0;
}

/**
 * @brief  销毁MQTT客户端
 */
void app_mqtt_destroy(void)
{   MQTTClient_disconnect(client, 0);
    MQTTClient_destroy(&client);
    log_info("MQTTClient_destroy\n");
}
